/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.freemarker.method;

import vip.dexian.common.utils.FreeMarkerUtils;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 字符截取
 *
 * @author 挺好的 2022年02月19日 13:59
 */
@Component ("abbreviateMethod")
public class AbbreviateMethod implements TemplateMethodModelEx {


    private static final Pattern PATTERN = Pattern.compile("[\\u4e00-\\u9fa5\\ufe30-\\uffa0]");

    @Override
    @SuppressWarnings ("rawtypes")
    public Object exec (List arguments) throws TemplateModelException {
        // 要缩写的字符串
        String str = FreeMarkerUtils.getArgument(0, String.class, arguments);
        // 截取多少个字符
        Integer width = FreeMarkerUtils.getArgument(1, Integer.class, arguments);
        // 截取后要展示的字符，如省略号：。。。
        String ellipsis = FreeMarkerUtils.getArgument(2, String.class, arguments);

        if (StringUtils.isEmpty(str) || width == null) {
            return str;
        }
        int i = 0;
        for (int strWidth = 0; i < str.length(); i++) {
            strWidth = AbbreviateMethod.PATTERN.matcher(String.valueOf(str.charAt(i)))
                    .find() ? strWidth + 2 : strWidth + 1;
            if (strWidth == width) {
                break;
            } else if (strWidth > width) {
                i--;
                break;
            }
        }
        return ellipsis != null && i < str.length() - 1 ? StringUtils.substring(str, 0,
                i + 1
        ) + ellipsis : StringUtils.substring(str, 0, i + 1);
    }
}
